package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.*;
import com.itheima.service.DeptService;
import com.itheima.service.StudentService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {
    @Resource
    private DeptService deptService;
    @Resource
    private StudentMapper studentMapper;

    @Override
    public PageResult<Student> pageStudent(StudentQueryParam student) {
        Page<Student> page = Page.of(student.getPage(), student.getPageSize());
        String name = student.getName();
        Page<Student> studentPage = lambdaQuery().like(name != null && !name.isEmpty(), Student::getName, name)
                .eq(student.getDegree() != null, Student::getDegree, student.getDegree())
                .page(page);
        List<Student> studentList = studentPage.getRecords();
        List<Integer> list = studentList.stream().map(student1 -> {
            return student1.getClazzId();
        }).toList();
        List<Dept> depts = deptService.listByIds(list);
        studentList.forEach(s->{
            depts.forEach(dept -> {
                if (s.getClazzId()!=null && s.getClazzId().equals(dept.getId())){
                    s.setClazzName(dept.getName());
                }
            });
        });
        return new PageResult<>(studentPage.getTotal(),studentPage.getRecords());
    }

    @Override
    public void saveStudent(Student student) {
        //新增学生
        student.setCreateTime(LocalDateTime.now());
        student.setUpdateTime(LocalDateTime.now());
        save(student);

    }

    @Override
    public Student getStudentById(Integer id) {
        //查询学生
        Student student = getById(id);
        //查询班级
        Integer clazzId = student.getClazzId();
        if (clazzId!=null){
            Dept dept = deptService.getById(clazzId);
            student.setClazzName(dept.getName());
        }
        return student;
    }

    @Override
    public void updateStudentById(Student student) {
        //修改学生信息
        student.setUpdateTime(LocalDateTime.now());
        updateById(student);
    }

    @Override
    public void removeStudentById(List<Integer> ids) {
        //删除学生
        removeBatchByIds(ids);
    }

    @Override
    public void violation(Integer id, Integer score) {
        //扣分
        LambdaUpdateWrapper<Student> warpper=new LambdaUpdateWrapper<>();
        warpper.eq(Student::getId,id);
        studentMapper.updateScore(warpper,score);
    }

}
